<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>生成验证码及其校验</title>
    <style>
        *{
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        .container{
            margin: 25px 50%;
            height:800px;
            width:500px;
        }
        #k{
            background-color: antiquewhite;
            width: 150px;
            height:50px;
            text-align: center;
            line-height: 50px;
        }
        #code{
            font-size: 30px;
            color: blue
        }
    </style>
  </head>
  <body>
    <div class="container">
        <div id="k">
            <span id="code">adf34y</span>
        </div>
        <div id="change-k">
            <span id="change">看不清换一张</span>
        </div>
        验证码：<input type="text" id="input">
        <button id="btn">确定</button>
    </div>
 
  </body> 
    <script>
        window.onload = function(){
            let arr =['0','1','2','3','4','5','6','7','8','9','a','s','d','f','g','h'];
            let res = getcode();

            function getcode(){
                var str = '';
                for( var i = 0 ; i < 6 ; i++){
                    let num = Math.round(Math.random()*15);
                    let onecode = arr[num];
                    str += onecode;
                }
                return str;
            }
                
            document.getElementById('code').innerHTML = res;

            //点击事件
            document.getElementById('change').onclick = function(){
                document.getElementById('code').innerHTML = getcode();
            }

            //提交之后进行对比，看验证码是否正确
            document.getElementById('btn').onclick = function(){
               var code = document.getElementById('code').innerText;
               var input = document.getElementById('input').value;
               if(code != input){
                alert("您输入的验证码不正确");
                document.getElementById("input").value = '';
                document.getElementById('code').innerHTML = getcode();//再次生成新的验证码

               }else{
                location.href = 'https://www.baidu.com/';
               }
            }

        }
        

    </script>
</html>